package com.shuoyue.ycgk.ui.common.download;

import android.util.Log;

import com.shuoyue.ycgk.base.BaseModel;
import com.shuoyue.ycgk.base.BasePresenter;
import com.shuoyue.ycgk.base.BaseView;
import com.shuoyue.ycgk.net.RetrofitClient;
import com.shuoyue.ycgk.net.base.filedownload.DownloadHelper;

import java.io.File;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public interface DownloadContract {
    interface View extends BaseView {

        void downloadSuc(File f);

        void progress(int progress);

        void downloadStart();

        void downloadError(String msg);
    }

    class Presenter extends BasePresenter<View> {
        Model model = new Model();

        public void downloadFile(String url, String savePath) {
            File file = new File(savePath);
            if (file.exists()) {
                file.delete();
            }
            model.downloadFile(url, new DownloadHelper.DownloadApkListener() {
                @Override
                public void onStart() {
                    Log.e("下载进度", "开始下载");
                    mView.downloadStart();
                }

                @Override
                public void onProgress(int p) {
                    Log.e("下载进度", "" + p);
                    mView.progress(p);

                }

                @Override
                public void onFinish(String path) {
                    File file = new File(path);
                    if (file.exists()) {
                        mView.downloadSuc(file);
                    }
                }

                @Override
                public void onError(String msg) {
                    Log.e("下载错误", msg);
                    mView.downloadError(msg);
                }
            }, savePath);
        }
    }


    class Model extends BaseModel {


        public void downloadFile(String url, final DownloadHelper.DownloadApkListener downloadApkListener, String savePath) {
            RetrofitClient.getInstance().getApi().downloadFileUrl(url).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()) {
                        new Thread(new DownloadHelper.FileDownloadRun(response, downloadApkListener, savePath)).start();
                    } else {
                        downloadApkListener.onError("连接超时");
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    downloadApkListener.onError(t.getMessage());
                }

            });


        }
    }

}
